package com.opengroupe.resources;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.opengroupe.dto.ReponseDto;
import com.opengroupe.entities.Reponse;
import com.opengroupe.service.common.CrudService;
import com.opengroupe.service.pc.PCService;
import com.opengroupe.utils.QrhWsUtils;

@Service("reponseResource")
@Path("/reponse")
public class ReponseResource {
	
	@Autowired
	private CrudService crudService;
	
	@Autowired
	private PCService pcService;
	
	private Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
	
	@GET
	@Produces("application/json")
	@Path("/getAll")
	public String getAllReponses(){
		
		@SuppressWarnings("unchecked")
		List<Reponse> reponses = (List<Reponse>) crudService.read(Reponse.class.getCanonicalName());
		
		List<ReponseDto> reponseDtos = new ArrayList<ReponseDto>();
		for(Reponse reponse : reponses){
			reponseDtos.add(QrhWsUtils.convertReponseToReponseDto(reponse));
		}
		return gson.toJson(reponseDtos);
	}
	
	@DELETE
	@Produces("application/json")
	@Path("/delete")
	@Transactional
	public void deleteReponse(String idReponse) throws Exception{
		try {
			pcService.deleteReponse(idReponse);
		} catch (Exception e) {
			throw e;
		}
	}
	
	@GET
	@Produces("application/json")
	@Path("/create")
	public String createReponse(@QueryParam("contenuReponse") String contenuReponse) throws Exception{
		Reponse reponse = new Reponse();
		reponse.setContenuReponse(contenuReponse);
		
		try {
			reponse = pcService.creerReponse(reponse);
		} catch (Exception e) {
			throw e;
		}
		
		ReponseDto reponseDto = QrhWsUtils.convertReponseToReponseDto(reponse);
		
		return gson.toJson(reponseDto, ReponseDto.class);
	}
	
	@GET
	@Produces("application/json")
	@Path("/update")
	public String updateReponse(@QueryParam("idReponse") String idReponse, @QueryParam("contenuReponse") String contenuReponse) throws Exception{
		
		Reponse reponse = (Reponse) crudService.read(Integer.parseInt(idReponse), Reponse.class.getCanonicalName());
		reponse.setContenuReponse(contenuReponse.trim());
		
		try{
			reponse = pcService.modifierReponse(reponse);
		} catch(Exception e){
			throw e;
		}
		
		ReponseDto reponseDto = QrhWsUtils.convertReponseToReponseDto(reponse);
		
		return gson.toJson(reponseDto, ReponseDto.class);
	}
}
